<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/23
 * Time: 11:13
 */

namespace app\admin\controller;

use app\admin\model\ShopHorn;
use app\admin\model\Gift;
use app\admin\model\Vehicle;
use app\admin\model\User;
use app\admin\model\Card;
use think\cache\driver\Redis;
use app\admin\model\SignRule as SignRuleModel;
class SignRule extends Index
{
    /**
     * @return \think\response\View
     * @user shuaishuai wu
     * @date 2018/11/23
     * @time 11:04
     * @title 签到规则
     *
     */
    public function signRuleIndex()
    {
        $giftType = [1 => '金币', '钻石', '座驾', '礼物', '喇叭', '生肖卡', '自定义'];
        $return = [];
        foreach($giftType as $key=>$value){
            $return[$key]['k'] = $key;
            $return[$key]['v'] = $value;
        }
        return view()->assign('return',$return);
    }

    /**
     * @return \think\response\Json
     * @user shuaishuai wu
     * @date 2018/11/23
     * @time 11:16
     * @title 签到规则数据
     */
    public function signRuleIndexData()
    {
        $signRuleModel = new SignRuleModel();
        $data = $signRuleModel->getDataList();
        return json($data);
    }

    /**
     * @user 帅帅
     * @date 2018/11/26
     * @time 9:37
     * @title  添加修改规则
     */
    public function signRuleAdd()
    {
        $signRuleModel = new SignRuleModel();
        $newData = input('post.');
        try{
            if($newData['reward_type'] == 7){
                $newData['custom'] = uniqid('custom_',true);
            }else{
                $newData['custom'] ='';
            }
            $signRuleModel->save($newData);
        }catch(\Exception $e){
            return ['code' => -100, 'msg' => '添加失败'];
        }
        return ['code' => 100, 'msg' => '添加成功'];
    }

    /**
     * @return array|\think\response\Redirect
     * @user shuaishuai wu
     * @date 2018/11/26
     * @time 15:10
     * @title 签到规则上架下架
     */
    public function signRuleChangeStatus()
    {
        if(request()->isGet()){
            $signRuleModel = new SignRuleModel();
            $signRuleDetail = $signRuleModel->where('id',input('get.id'))->find();
            $newData['status'] = $signRuleDetail['status'] === 1 ? 0 : 1;
            try{
                $signRuleModel->save($newData,['id'=>input('get.id')]);
            }catch(\Exception $e){
                $this->error(lang('edit').lang('false').$e->getMessage());
            }
            return ['code'=>200,'msg'=>'修改成功'];
        }
        return redirect('/Miss');
    }
    /**
     * @return $this
     * @user shuaishuaiwu
     * @date 2018/11/25
     * @time 19:59
     * @title 渲染修改页面，奖品类型
     */
    public function signRuleEdit()
    {
        if(request()->isGet()){
            $id = input('get.id');
            $giftType = [1 => '金币', '钻石', '座驾', '礼物', '喇叭', '生肖卡', '自定义'];
            foreach($giftType as $key=>$value){
                $return[$key]['k'] = $key;
                $return[$key]['v'] = $value;
            }
            $ruleData = SignRuleModel::where('id','=',$id)->find();
            switch($ruleData['reward_type']){
                case 3: $ruleData['gift_name'] = Vehicle::where('vehicle_id','=',$ruleData['reward_id'])->value('vehicle_name');break;
                case 4: $ruleData['gift_name'] = Gift::where('id','=',$ruleData['reward_id'])->value('gift_name');break;
                case 5: $ruleData['gift_name'] = ShopHorn::where('horn_id','=',$ruleData['reward_id'])->value('horn_name');break;
                case 6: $ruleData['gift_name'] = Card::where('id','=',$ruleData['reward_id'])->value('name');break;
                default:$ruleData['gift_name'] = '';
            }
            $ruleData['type_name'] = $giftType[$ruleData['reward_type']];
            return view()->assign(['return'=>$return,'ruleData'=>$ruleData]);
        }

    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @user shuaishuai wu
     * @date 2018/11/25
     * @time 20:20
     * @title 修改页面的奖品名称
     */
    public function signRuleGiftName(){
        if (request()->isPost()) {
            $type = input('post.giftType');
            switch($type){
                case 3:
                    $returnData = Vehicle::field('vehicle_id,vehicle_name')->select();
                    foreach($returnData as $key =>$value){
                        $return[$key]['id'] = $value['vehicle_id'];
                        $return[$key]['gift_name'] = $value['vehicle_name'];
                    }
                    break;
                case 4:
                    $returnData = Gift::field('id,gift_name')->select();
                    foreach($returnData as $key =>$value){
                        $return[$key]['id'] = $value['id'];
                        $return[$key]['gift_name'] = $value['gift_name'];
                    }
                    break;
                case 5:
                    $returnData = ShopHorn::field('horn_id,horn_name')->select();
                    foreach($returnData as $key =>$value){
                        $return[$key]['id'] = $value['horn_id'];
                        $return[$key]['gift_name'] = $value['horn_name'];
                    }
                    break;
                case 6:
                    $returnData = Card::field('id,name')->select();
                    foreach($returnData as $key =>$value){
                        $return[$key]['id'] = $value['id'];
                        $return[$key]['gift_name'] = $value['name'];
                    }
                    break;
                default:$return='';
            }
            return $return;
        }
        return redirect('/Miss');
    }

    /**
     * @return array|\think\response\Redirect
     * @user 帅帅
     * @date 2018/11/25
     * @time 22:50
     * @title 提交修改规则
     */
    public function signRuleSubmitEdit()
    {
        if(request()->isGet()){
            $newData = input('get.');
            if(empty($newData['reward_id'])){
                $newData['reward_id'] = null;
            }
            if($newData['reward_type'] == 7 && empty( $newData['custom'])){
                $newData['custom'] = uniqid('custom_',true);
            }else{

                $newData['custom'] = '';
            }
            $signRuleModel = new SignRuleModel();
            try{
                 $signRuleModel->save($newData,['id'=>$newData['id']]);
            }catch(\Exception $e){
                return ['code' => -100, 'msg' => '修改失败'];
            }
            return ['code' => 100, 'msg' => '修改成功'];
        }
        return redirect('/Miss');
    }

    /**
     * @return $this
     * @user shuaishuai
     * @date 2018/11/24
     * @time 16:19
     * @title 自定义内容信息
     */
    public function signRuleVehicleIndex()
    {
        $redisKey = input('get.custom');
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $data = json_decode($redis->get($redisKey),true);
        $arr = [1 => '金币', '钻石', '座驾', '礼物', '喇叭', '生肖卡'];
        foreach ($arr as $key => $value) {
            $giftType[$key]['k'] = $key;
            $giftType[$key]['v'] = $value;
        }
        if(empty($data)){
            $returnData = [];
        }else {
            foreach ($data as $key => $value) {
                $returnData[$key]['key'] = $key;
                $returnData[$key]['sum'] = count($value['default_user']);
                $returnData[$key]['type'] = $arr[$value['type']] ? $arr[$value['type']] : '未知'; //如果redis的type大于7则为未知
                switch ($value['type']) {
                    case 3:
                        $returnData[$key]['gift_name'] = Vehicle::where('vehicle_id', '=', $value['type_id'])->value('vehicle_name');
                        break;
                    case 4:
                        $returnData[$key]['gift_name'] = Gift::where('id', '=', $value['type_id'])->value('gift_name');
                        break;
                    case 5:
                        $returnData[$key]['gift_name'] = ShopHorn::where('horn_id', '=', $value['type_id'])->value('horn_name');
                        break;
                    case 6:
                        $returnData[$key]['gift_name'] = Card::where('id', '=', $value['type_id'])->value('name');
                        break;
                    default:
                        $returnData[$key]['gift_name'] = $value['type_id'];
                }
                $returnData[$key]['type_id'] = $value['type_id'];
                $returnData[$key]['default_stock'] = $value['default_stock'];
                $returnData[$key]['prize_stock'] = $value['prize_stock'];
            }
        }
        return view()->assign(['returnData'=>$returnData,'redisKey'=>$redisKey,'giftType'=>$giftType]);
    }

    /**
     * @return $this
     * @user shuaishuai
     * @date 2018/11/24
     * @time 16:20
     * @tilte 默认用户列表
     */
    public function signRuleDefaultUserIndex()
    {
        $redisKey = input('get.redisKey');
        $arrKey = input('get.arrKey');
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $data = json_decode($redis->get($redisKey),true);
        $userIds = $data[$arrKey]['default_user'];
        $userInfo = [];
        foreach($userIds as $k=>$v){
            $userInfo[$k]['id'] = User::where('id','=',$v)->value('id');
            $userInfo[$k]['u_id'] = User::where('id','=',$v)->value('u_id');
            $userInfo[$k]['nickname'] = User::where('id','=',$v)->value('nickname');
            $userInfo[$k]['pic'] = User::where('id','=',$v)->value('pic');
        }
        return view()->assign('data',$userInfo);
    }

    /**
     * @return $this
     * @user shuaishusai
     * @date 2018/11/24
     * @time 16:22
     * @title 修改自定义信息
     */
    public function signRuleEditDefineContent()
    {
        $redisKey = input('get.redisKey');
        $arrKey = input('get.arrKey');
       // $prizeStock = input('get.prizeStock');
        $defaultStock = input('get.defaultStock');
       // $arrKey -= 1;
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $data = json_decode($redis->get($redisKey),true);
        $userIds = $data[$arrKey]['default_user'];
        $userIds_str = implode(',',$userIds);
        return view()->assign([
            'arrKey'=>$arrKey,
            'redisKey'=>$redisKey,
            'defaultStock'=>$defaultStock,
            'userIds_str'=>$userIds_str
        ]);
    }

    /**
     * @return array
     * @user shuaishuai
     * @date 2018/11/24
     * @time 16:23
     * @title 提交修改自定义信息
     */
    public function SignRuleSubmitDefineContent()
    {
        $redisKey = input('get.redisKey');
        $arrKey = input('get.arrKey');
     //   $arrKey -= 1;
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $data = json_decode($redis->get($redisKey), true);
        $default_stock = input('get.default_stock');
       // $prize_stock = input('get.prize_stock');
        $default_user = input('get.default_user');

        if(!isset($default_stock))
            return ['code' => -100, 'msg' => '请填写默认库存'];
        $data[$arrKey]['default_stock'] = (int)$default_stock;
        if(empty($default_user)){
            $data[$arrKey]['default_user'] = [];
        }else{
            $data[$arrKey]['default_user'] = explode(',', $default_user);
        }
        $res = $redis->set($redisKey, json_encode($data));
        if ($res)
            return ['code' => 100, 'msg' => '修改成功'];
        else
            return ['code' => -100, 'msg' => '修改失败'];
    }

    /**
     * @return array
     * @user shuaishuai wu
     * @date 2018/11/26
     * @time 10:22
     * @title 删除自定义内容
     */
    public function signRuleDelDefineContent()
    {
        $redisKey = input('get.redisKey');
        $arrKey = input('get.arrKey');
        $redis = new \Redis();
        $redis->connect(config('app.redis.host'), 6379);
        $redis->auth(config('app.redis.pwd'));
        $data = json_decode($redis->get($redisKey), true);
        if(!empty($data[$arrKey])){
            unset($data[$arrKey]);
            $res = $redis->set($redisKey, json_encode($data));
            if($res){
                return ['code'=>100,'msg'=>'删除成功'];
            }
            return ['code'=>-100,'msg'=>'删除失败'];
        }
            return ['code'=>-100,'msg'=>'删除失败,键名不存在'];
    }

    /**
     * @return array|\think\response\Redirect
     * @user shuaishguai wu
     * @date 2018/11/26
     * @time 14:28
     * @title 添加自定義内容
     */
    public function signRuleAddDefineContent()
    {
        if(request()->isPost()){
            $redisKey = input('post.redisKey');
            $arr['type'] = input('post.type');
            $arr['type_id'] =input('post.type_id');
            $arr['default_stock'] = input('post.default_stock');
            $arr['prize_stock'] = input('post.prize_stock');
            $default_user = input('post.default_user',[]);
            if(empty($default_user)){
                $arr['default_user'] = [];
            }else{
                $arr['default_user'] = explode(',',$default_user);
            }


            $arr['default_user'] = explode(',',$default_user);
            $redis = new \Redis();
            $redis->connect(config('app.redis.host'), 6379);
            $redis->auth(config('app.redis.pwd'));
            $data = json_decode($redis->get($redisKey), true);
            try{
                if(!empty($data)){
                    $k = 0;
                    foreach($data as $key=>$value){
                        if($key>$k){
                            $k = $key;
                        }
                    }
                    $k+=1;
                    $data[$k]=$arr;  //友情提示,array_push()不太友好,此处用if..else..处理
                }else{
                    $data[1]=$arr;
                }
                $res = $redis->set($redisKey, json_encode($data));
            }catch(\Exception $e){
                return ['code'=>-100,'msg'=>'添加失败','data'=>$data];
            }
            if($res){
                return ['code'=>100,'msg'=>'添加成功','data'=>$data,'res'=>$arr];
            }
        }
        return redirect('/Miss');
    }
}